package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;

import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.databinding.ActivityFileProBinding;
import flc.ast.utils.Content;

public class FileProActivity extends BaseAc<ActivityFileProBinding> {

    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private DeviceAdapter deviceAdapter;
    private int oldPosition;
    private Dialog myProDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_file_pro;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileProBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        deviceAdapter = new DeviceAdapter();
        mDataBinding.rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.addChildClickViewIds(R.id.tvDeviceItemSel);
        deviceAdapter.addChildClickViewIds(R.id.tvDeviceItemNotSel);
        deviceAdapter.setOnItemChildClickListener(this);

        mDataBinding.ivSearchDevice.setOnClickListener(this);
        mDataBinding.tvStartPro.setOnClickListener(this);
        //投屏弹框
        proDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivSearchDevice:
                if (Content.IsConnect) {
                    Content.IsConnect = false;
                    deviceAdapter.getItem(oldPosition).setConnect(false);
                    deviceAdapter.notifyDataSetChanged();
                    mCastScreenManager.disConnect();
                    Content.ConnectName = "";
                    mDataBinding.tvProStatus.setText(getString(R.string.not_conn));
                    mDataBinding.tvProStatus.setTextColor(Color.parseColor("#000000"));
                    mDataBinding.tvProName.setText(getString(R.string.not_conn));
                    mDataBinding.tvProName.setTextColor(Color.parseColor("#A2A2A2"));
                    mDataBinding.ivSearchDevice.setImageResource(R.drawable.asousuosheb);
                } else if (!isSearch) {
                    startSearch();
                }
                break;
            case R.id.tvStartPro://开始投屏
                myProDialog.show();
                break;
            //投屏弹框
            case R.id.ivDialogProImg://图片
                startActivity(ProSelPicActivity.class);
//                gotoPro(ProSelPicActivity.class);
                break;
            case R.id.ivDialogProVideo://视频
                startActivity(ProVideoActivity.class);
//                gotoPro(ProVideoActivity.class);
                break;
            case R.id.ivDialogProAudio://音频
                startActivity(ProAudioActivity.class);
//                gotoPro(ProAudioActivity.class);
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.tvDeviceItemNotSel:
                Content.IsConnect = true;
                deviceAdapter.getItem(oldPosition).setConnect(false);
                oldPosition = position;
                deviceAdapter.getItem(position).setConnect(true);
                deviceAdapter.notifyDataSetChanged();
                mCastScreenManager.connect(deviceAdapter.getItem(position));
                Content.ConnectName = deviceAdapter.getItem(position).getName();
                mDataBinding.tvProStatus.setText(getString(R.string.conn_suc));
                mDataBinding.tvProStatus.setTextColor(Color.parseColor("#39EE66"));
                mDataBinding.tvProName.setText(Content.ConnectName);
                mDataBinding.tvProName.setTextColor(Color.parseColor("#010101"));
                mDataBinding.ivSearchDevice.setImageResource(R.drawable.aduankailj);
                break;
            case R.id.tvDeviceItemSel:
                Content.IsConnect = false;
                deviceAdapter.getItem(position).setConnect(false);
                deviceAdapter.notifyDataSetChanged();
                mCastScreenManager.disConnect();
                Content.ConnectName = "";
                mDataBinding.tvProStatus.setText(getString(R.string.not_conn));
                mDataBinding.tvProStatus.setTextColor(Color.parseColor("#000000"));
                mDataBinding.tvProName.setText(getString(R.string.not_conn));
                mDataBinding.tvProName.setTextColor(Color.parseColor("#A2A2A2"));
                mDataBinding.ivSearchDevice.setImageResource(R.drawable.asousuosheb);
                break;
        }
    }

    @Override
    protected void initData() {
        //注册投屏
        registerScreen();
    }

    //去到投屏界面
    private void gotoPro(Class cls) {
        if (!Content.IsConnect) {
            ToastUtils.showShort(R.string.please_conn_pro_device);
            return;
        }
        startActivity(cls);
    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                ToastUtils.showShort(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
//                    startSearch();
                } else {
                    Content.IsInit = false;
                }

            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                mDataBinding.llSearch.setVisibility(View.VISIBLE);
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        mDataBinding.rvDeviceList.setVisibility(View.VISIBLE);
                        mDataBinding.tvSearchNoData.setVisibility(View.GONE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        mDataBinding.rvDeviceList.setVisibility(View.GONE);
                        mDataBinding.tvSearchNoData.setVisibility(View.VISIBLE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showShort(getString(R.string.search_over));
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showShort(getString(R.string.auth_def));
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (Content.IsInit) {
//            isSearch = true;
//            startSearch();
        } else {
            showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }

    //搜索
    private void startSearch() {
        isSearch = true;
        showDialog(getString(R.string.search_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mCastScreenManager.startBrowse();
            }
        }, 500);
    }

    //投屏弹框
    private void proDialog() {
        myProDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_pro, null);
        myProDialog.setContentView(inflate);
        myProDialog.setCancelable(true);
        Window dialogWindow = myProDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView img = inflate.findViewById(R.id.ivDialogProImg);
        ImageView video = inflate.findViewById(R.id.ivDialogProVideo);
        ImageView audio = inflate.findViewById(R.id.ivDialogProAudio);
        img.setOnClickListener(this);
        video.setOnClickListener(this);
        audio.setOnClickListener(this);
    }

}